package ar.uba.fi.tonyvaliente.persistors;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import ar.uba.fi.tonyvaliente.files.Persistor;
import ar.uba.fi.tonyvaliente.files.PersistorException;
import ar.uba.fi.tonyvaliente.files.RecordPosition;

public class RecordPositionPersistor extends Persistor<RecordPosition> {

	@Override
	public RecordPosition deserialize(byte[] bytes) throws PersistorException {

		RecordPosition position = null;

		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		DataInputStream in = new DataInputStream(bais);

		// Leo cantidad de elementos
		try {
			int blockNumber = in.readInt();
			int offset = in.readInt();
			position = new RecordPosition(blockNumber, offset);
		} catch (IOException e) {
			e.printStackTrace();
			throw new PersistorException("Error desserializando la posición ", e);
		}
		
		return position;
	}

	@Override
	public byte[] serialize(RecordPosition position) throws PersistorException {
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream out = new DataOutputStream(baos);

			int blockNumber = position.getBlockNumber();
			int offset = position.getOffset();
			
			try {
				out.writeInt(blockNumber);
				out.writeInt(offset);
			} catch (IOException e) {
				e.printStackTrace();
				throw new PersistorException("Error serializando la posición " + position, e);
			}
		
		return baos.toByteArray();
	}

}
